package com.jf.service.impl;


import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf.enums.OrderEnum;
import com.jf.mapper.UserOrderMapper;
import com.jf.pojo.AlipayBean;
import com.jf.pojo.UserOrder;
import com.jf.util.AliPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private AliPayUtil aliPayUtil;


    public String orderPay(BigDecimal orderAmount) throws AlipayApiException {
        //1. 产生订单
        UserOrder order = new UserOrder();
        order.setOrderNo(System.currentTimeMillis() + "");
        order.setUserId(UUID.randomUUID().toString());
        order.setOrderAmount(orderAmount);
        order.setOrderStatus(OrderEnum.ORDER_STATUS_NOT_PAY.getStatus());
        order.setCreateTime(new Date());
        order.setLastUpdateTime(new Date());
        userOrderMapper.insert(order);


        //调用支付宝
        //2. 调用支付宝
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(order.getOrderNo());
        alipayBean.setSubject("充值:" + order.getOrderAmount());
        alipayBean.setTotal_amount(orderAmount.toString());
        String pay = aliPayUtil.pay(alipayBean);
        System.out.println("pay:" + pay);
        return pay;
    }


    /**
     * 67      * 根据订单号查询订单
     * 68      *
     * 69      * @param orderNo
     * 70      * @return 返回订单信息
     * 71
     */
    public UserOrder getOrderByOrderNo(String orderNo) {
        return userOrderMapper.selectOne(new LambdaQueryWrapper<UserOrder>().eq(UserOrder::getOrderNo,orderNo));
    }

    /**
     * 80      * 更新订单
     * 81      *
     * 82      * @param userOrder 订单对象
     * 83      * @return 返回更新结果
     * 84
     */
    public int updateOrder(UserOrder userOrder) {
        return userOrderMapper.updateById(userOrder);
    }
}
